/**
 * 音乐相关控制逻辑
 */
const path = require('path')

const express = require('express')
const formidable = require('formidable')

const fs = require('../../libs/fs')
const Search = require('../../models/search')
const User = require('../../models/user')

const router = module.exports = express.Router()

router.prefix = '/admin/search'

/**
 * GET /search
 */
router.get('/', async(req, res) => {

    const list = await Search.findAll({
        include: { model: User, as: 'user' }
    })

    res.locals.title = '搜索列表'
    res.locals.list = list
    res.render('admin/search/list')

})

/**
 * GET /search/add
 */
router.get('/add', async(req, res) => {

    const users = await User.findAll()

    res.locals.title = '添加新搜索'
    res.locals.users = users
    res.render('admin/search/add')

})

/**
 * POST /search/add
 */
router.post('/add', (req, res) => {
    const form = new formidable.IncomingForm()
    let upload_dir = path.join(global.UPLOAD_PATH, 'search');
    fs.mkdirsSync(upload_dir)
    form.uploadDir = upload_dir
    form.keepExtensions = true
    form.parse(req, (error, fields, files) => {
        if (error) throw error
            // 接收到客户端提交过来文件和填写的信息

        Search.create({
            name: fields.name,
            userId: fields.userId,
        })

        res.redirect('/admin/search')

    })


})

/**
 * GET /search/edit/:id
 */
router.get('/edit/:id', async(req, res) => {
    res.locals.title = '编辑'
        // 接收传过来的ID
    const id = parseInt(req.params.id || 0)
    if (!id) {
        // 不存在这个数据
        return res.status(404).send('没有该记录')
    }
    // 找到数组中的这个元素删除
    const search = await Search.findByPk(id)

    if (!search) {
        // 不存在这个数据
        return res.status(404).send('没有该记录')
    }

    const users = await User.findAll()
    res.locals.users = users
    res.locals.item = search
    res.render('admin/search/edit')


})

/**
 * POST /search/edit/:id
 */
router.post('/edit/:id', async(req, res) => {
    res.locals.title = '编辑'
        // 接收传过来的ID
    const id = parseInt(req.params.id || 0)
    if (!id) {
        // 不存在这个数据
        return res.status(404).send('没有该记录')
    }
    // 找到数组中的这个元素删除
    const search = await Search.findByPk(id)
    if (!search) {
        // 不存在这个数据
        return res.status(404).send('没有该记录')
    }

    search.update({
        name: req.body.name,
        userId: req.body.userId,
    }).then(data => {
        res.redirect('/admin/search')
    }).catch(error => {
        console.log(error)
    })


})

/**
 * GET /search/delete/:id
 */
router.get('/delete/:id', async(req, res) => {
    // 接收传过来的ID
    const id = parseInt(req.params.id || 0)
    if (!id) {
        // 不存在这个数据
        return res.status(404).send('没有该记录')
    }
    // 找到数组中的这个元素删除
    Search.destroy({
        where: {
            id: id
        }
    }).then(() => {
        res.redirect('/admin/search')
    })



})